package com.easy.util;

import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ExpiryMap {
    // 用来储存数据的容器
    private java.util.Map<String, Object> map = new java.util.HashMap<String, Object>();
    //存储数据的有效期
    private Map<String, Long>expriyMap=new java.util.HashMap<String, Long>();

    //检查过期线程(池)
    private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    //检查周期
    private long expiryTime = 1000 * 6;
    public ExpiryMap() {
        service.scheduleAtFixedRate(this::clearExpiry,expiryTime,expiryTime, TimeUnit.MILLISECONDS);
    }

    public ExpiryMap(long expiryTime) {
        this.expiryTime = expiryTime;
        service.scheduleAtFixedRate(this::clearExpiry,expiryTime,expiryTime, TimeUnit.MILLISECONDS);
    }

    public void put(String key,Object value){
        map.put(key, value);
        expriyMap.put(key, System.currentTimeMillis()+expiryTime);
    }
    public void put(String key,Object value,long expiryTime){
        map.put(key, value);
        expriyMap.put(key, System.currentTimeMillis()+expiryTime);
    }

    public Object get(String key){
        if(expriyMap.get(key)!=null&&expriyMap.containsKey(key)){
            if(System.currentTimeMillis()-expriyMap.get(key)>expiryTime){
                map.remove(key);
                expriyMap.remove(key);
            }
        }
        return map.get(key);
    }
    public void remove(String key){
        map.remove(key);
        expriyMap.remove(key);
    }

    public boolean containsKey(String key){
        if(expriyMap.get(key)<System.currentTimeMillis()){

                map.remove(key);
                expriyMap.remove(key);

        }
        return map.containsKey(key);
    }

    //清除过期数据key
    public void clearExpiry(){
        for(String key:expriyMap.keySet()){
            if(System.currentTimeMillis()-expriyMap.get(key)>expiryTime){
                map.remove(key);
                expriyMap.remove(key);
            }
        }

    }

}
